/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package BackEnd;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.ws.Action;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;


/**
 *
 * @author Gabi
 */

public class Linker {



    private Linker(){

    }



    public static Document getData(String sUrl,String function,String method,String [] args) throws Exception {

            // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html

        String serviceUrl = sUrl;

        URL url;
        URLConnection urlc=null;

        String pargs=parseArgs(args);

        if (method.equals("GET")){
        	url = new URL(serviceUrl+"?method="+function+"&"+pargs);
            urlc = url.openConnection();
            urlc.setDoOutput(false);
            urlc.setAllowUserInteraction(false);
        }
        else if (method.equals("POST")){
	    url = new URL(serviceUrl+"?method="+function+"&"+pargs);

	    urlc = url.openConnection();
            urlc.setDoOutput(true);
            urlc.setAllowUserInteraction(false);
        }

        //retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

        String str;
        StringBuffer sb = new StringBuffer();

        while ((str = br.readLine()) != null) {
            sb.append(str);
            sb.append("\n");
        }
        br.close();
        String response = sb.toString();

        if (response == null) {
        	throw new Exception("Not Response From Server");
        }


        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(response));
        Document dom = db.parse(is);


        checkFail(dom);

        return dom;

    }

    private static String parseArgs(String[] args) {
    		
    	String allArgs="";
    	
    	if (args!=null){
	    	for(String a: args){
	    		allArgs=!allArgs.equals("")?allArgs+"&"+a:a;
	    	}
    	}

    	return allArgs;
    }
	

    private static void checkFail(Document dom) throws Exception{
    	
    	Node status = dom.getElementsByTagName("response").item(0).getAttributes().getNamedItem("status");
		
		if (status.getNodeValue().equals("fail")){
			
			NamedNodeMap error=dom.getElementsByTagName("error").item(0).getAttributes();
			
			String code=error.getNamedItem("code").getNodeValue();
			String descr=error.getNamedItem("message").getNodeValue();
//			System.out.println("codigo: "+code+" - descr: "+descr);
			throw new Exception ("codigo: "+code+" - descr: "+descr);
		}
    }

}
